package com.example.demo3network;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class RequestDataActivity extends AppCompatActivity {


    public static final String API_URL = "http://www.imooc.com/api/teacher?type=2&page=1";
    public static final String STATUS = "status";
    public static final String MSG = "msg";
    public static final String DATA = "data";
    ListView listView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_requestdata);
        findViews();
        setClickListeners();

        new RequestDataAsyncTask().execute();
    }


    private void findViews() {
        listView = (ListView) findViewById(R.id.requestDataListView);
    }

    private void setClickListeners() {


    }

    public class RequestDataAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // laoding消失，数据处理 刷新页面
            LesssonResult lessonResult = new LesssonResult();
            try {
                JSONObject jsonObject = new JSONObject(result);
                final int status = jsonObject.getInt(STATUS);
                lessonResult.setmStatus(status);
                final String msg = jsonObject.getString(MSG);
                lessonResult.setmMessage(msg);

                List<LessonInfo> lessonInfos = new ArrayList<>();
                JSONArray dataArray = jsonObject.getJSONArray(DATA);
                for (int index=0;index<dataArray.length();index++) {
                    LessonInfo lessonInfo = new LessonInfo();
                    JSONObject temJsonObject = (JSONObject) dataArray.get(index);
                    lessonInfo.setmName(temJsonObject.getString("name"));
                    lessonInfos.add(lessonInfo);
                }
                lessonResult.setLessonInfoList(lessonInfos);

            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            listView.setAdapter(new RequestDataAdapter(RequestDataActivity.this, lessonResult.getLessonInfoList()));
        }

        @Override
        protected String doInBackground(Void... voids) {
            return request(API_URL);
        }

        private String request(String urlString) {
            try {
                URL url = new URL(urlString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(30*1000);
                connection.setRequestMethod("GET");
                connection.connect();

                int responseCode = connection.getResponseCode();
                String responseMessage = connection.getResponseMessage();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line=bufferedReader.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    return stringBuilder.toString();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

    }



}
